package hci.project.model;

import android.graphics.Bitmap;
import android.graphics.Color;

public class LABImageIO {
	private LAB[][] LABImage;
	private int width;
	private int height;
	
	public LABImageIO(){
		this.LABImage=new LAB[0][0];
		this.width=0;
		this.height=0;
	}
	
	public int getImageWidth(){
		return this.width;
	}
	
	public int getImageHeight(){
		return this.height;
	}
	
	public void readImage(Bitmap img){
    	this.width=img.getWidth();
    	this.height=img.getHeight();   	
    	this.LABImage=new LAB[height][width];

    	double Yn = 100;
    	double Xn = 95.02;
    	double Zn = 108.82;
    	
    	for(int i=0;i<height;i++){
    		for(int j=0;j<width;j++){
    			int color=img.getPixel(j, i);
    			
    			int red=Color.red(color);
    			int green=Color.green(color);
    			int blue=Color.blue(color);
    			
    			
    			double X=(double)0.412453*red+0.357580*green+0.180423*blue;
    			double Y=(double)0.212671*red+0.715160*green+0.072169*blue;
    			double Z=(double)0.019334*red+0.119193*green+0.950227*blue;
    			
    			int L=(int)(116*labcheck(Y/Yn))-16;
    			int A=(int)(500*(labcheck(X/Xn) - labcheck(Y/Yn)));
    			int B=(int)(200*(labcheck(Y/Yn) - labcheck(Z/Zn)));
    			
    			LAB pixel=new LAB(L,A,B);		
    			this.LABImage[i][j]=pixel;

    		}
    	}
	}
	
	/*
	 *x: x value of pixel, 0 -- width, 0 is the left of image
	 *y: y value of pixel, 0 -- height, 0 is the top of image 
	 */
	public LAB getLAB(int x, int y){
		return this.LABImage[y][x];
	}
	
	private double labcheck(double q){
		double f=0;
		double m=1.0/3.0;
		if (q > 0.008856){
			f=java.lang.Math.pow(q, m);
		}
		else {
			f=7.787*q + (16/116);
		}

		return f;
	}
}
